package com.qingxin.sys.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;

import com.qingxin.sys.dao.Querier;
import com.qingxin.sys.dao.Updater;
import com.qingxin.sys.entity.LoginUser;
import com.qingxin.sys.entity.SysGroup;
import com.qingxin.sys.mvc.PageParam;
import com.qingxin.sys.mvc.Pager;
import com.qingxin.sys.mvc.SysError;
import com.qingxin.sys.support.SystemCfg;
import com.qingxin.sys.utils.BeanUtil;
import com.qingxin.sys.utils.StringUtils;
import com.qingxin.ui.bean.TreeNode;

/**
 * 分组管理
 * @author Administrator
 *
 */
@Service
public class SysGroupService extends BaseService<SysGroup, String> {
	
	/**
	 * 获取分组树
	 * @param pid
	 * @param datatype
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<TreeNode> getGroupTree(String pid, String datatype, Integer maxGroupType, LoginUser loginUser){
		if(StringUtils.isEmpty(pid) || pid.equals("-1")){
			pid = "0";
		}
		List<TreeNode> rslist = new ArrayList<>();
		
		String hql = "from SysGroup where pid=? ";
		if(maxGroupType != null){
			hql += " and grouptype <= "+maxGroupType;
		}
		if(!SystemCfg.isSystemAdminUser(loginUser)){
			hql += " and grouptype<>9 ";
		}
		hql += " order by groupname";
		
		List<SysGroup> list = listByHql(hql, pid);
		if(list != null){
			for(SysGroup group : list){
				TreeNode treeNode = new TreeNode(group.getGroupid(), group.getGroupname(), datatype, "groupid", true);
				treeNode.setCustdata(""+group.getGrouptype());
				rslist.add(treeNode);
			}
		}
		return rslist;
	}
	
	@SuppressWarnings("unchecked")
	public List<TreeNode> getGroupTreeNz(String pid, String datatype, LoginUser loginUser){
		if(StringUtils.isEmpty(pid) || pid.equals("-1")){
			pid = "0";
		}
		List<TreeNode> rslist = new ArrayList<>();
		
		String hql = "from SysGroup where pid=? ";
		hql += " and grouptype in (1,4) ";
		if(!SystemCfg.isSystemAdminUser(loginUser)){
			hql += " and grouptype<>9 ";
		}
		hql += " order by groupname";
		
		List<SysGroup> list = listByHql(hql, pid);
		if(list != null){
			for(SysGroup group : list){
				TreeNode treeNode = new TreeNode(group.getGroupid(), group.getGroupname(), datatype, "groupid", true);
				treeNode.setCustdata(""+group.getGrouptype());
				rslist.add(treeNode);
			}
		}
		return rslist;
	}
	
	
	@SuppressWarnings("unchecked")
	public List<TreeNode> getGroupTreeJc(String pid, String datatype, LoginUser loginUser){
		if(StringUtils.isEmpty(pid) || pid.equals("-1")){
			pid = "0";
		}
		List<TreeNode> rslist = new ArrayList<>();
		
		String hql = "from SysGroup where pid=? ";
		hql += " and grouptype in (1,5) ";
		if(!SystemCfg.isSystemAdminUser(loginUser)){
			hql += " and grouptype<>9 ";
		}
		hql += " order by groupname";
		
		List<SysGroup> list = listByHql(hql, pid);
		if(list != null){
			for(SysGroup group : list){
				TreeNode treeNode = new TreeNode(group.getGroupid(), group.getGroupname(), datatype, "groupid", true);
				treeNode.setCustdata(""+group.getGrouptype());
				rslist.add(treeNode);
			}
		}
		return rslist;
	}
	
	
	/**
	 * 获取分组列表
	 * @param pid
	 * @param search
	 * @param pageParam
	 * @param request
	 * @return
	 */
	public Pager list(String pid, String search, LoginUser loginUser, PageParam pageParam, HttpServletRequest request){
		if(StringUtils.isEmpty(pid) || pid.equals("-1")){
			pid = "0";
		}
		
		Querier querier = Querier.create("from SysGroup g where g.pid=:pid ");
		querier.setParam("pid", pid);
		
		if(!SystemCfg.isSystemAdminUser(loginUser)){
			querier.append(" and grouptype<>9 ");
		}
		
		if(StringUtils.isNotEmpty(search)){
			querier.append(" and g.groupname like :groupname ");
			querier.setParam("groupname", "%"+search.replace("'", "")+"%");
		}
		
		querier.append(pageParam.getOrderby(" order by g.createTime desc"));
		
		Pager pager = pageByQuerier(querier, pageParam);
		return pager;
	}
	
	
	/**
	 * 添加分组
	 * @param group
	 * @param loginUser
	 * @param request
	 * @return
	 */
	public SysError add(SysGroup group, LoginUser loginUser, HttpServletRequest request) {
		if(!group.getPid().equals("0")){
			SysGroup pGroup = get(group.getPid());
			if(pGroup == null){
				return new SysError("参数错误.");
			}
		}
		if(isNameDuplicate(group.getGroupname(), null, group.getPid())){
			return new SysError("分组名称已存在.");
		}
		
		String groupid = getNewGroupid(group.getPid());
		if(groupid == null){
			return new SysError("分组数量已达最大上限，无法添加.");
		}
		group.setGroupid(groupid);
		
		Date now = new Date();
		group.setCreateTime(now);
		group.setUpdateTime(now);
		group.setCreateBy(loginUser.getLogin_name());
		group.setUpdateBy(loginUser.getLogin_name());
		
		this.save(group);
		return null;
	}
	
	
	/**
	 * 获取分组ID
	 * @param pid
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String getNewGroupid(String pid){
		if(pid.equals("0")){
			List<String> ids = listByHql("select groupid from SysGroup where pid=? order by groupid", pid);
			if(ids == null || ids.size() == 0){
				return "1000";
			}
			final int len = ids.size();
			for(int i=0; i<9000; i++){
				if(i >= len || 1000 + i < Integer.parseInt(ids.get(i))){
					return String.valueOf(1000 + i);
				}
			}
		}else {
			List<String> ids = listByHql("select groupid from SysGroup where pid=? order by groupid", pid);
			if(ids == null || ids.size() == 0){
				return pid+"0000";
			}
			final int len = ids.size();
			final int pidlen = pid.length();
			for(int i=0; i<10000; i++){
				if(i >= len || i < Integer.parseInt(ids.get(i).substring(pidlen))){
					return pid + String.format("%04d", i);
				}
			}
		}
		return null;
	}
	
	
	/**
	 * 更新分组信息
	 * @param group
	 * @param loginUser
	 * @param request
	 * @return
	 */
	public SysError update(SysGroup group, LoginUser loginUser, HttpServletRequest request){
		SysGroup oldGroup = get(group.getGroupid());
		if(oldGroup==null){
			return new SysError("分组不存在");
		}
		
		if(isNameDuplicate(group.getGroupname(), group.getGroupid(), group.getPid())){
			return new SysError("分组名称已存在.");
		}
		
		String fields = "groupname,remark,grouptype";
		BeanUtil.setTargetFields(oldGroup, group, fields, true);
		
		oldGroup.setUpdateBy(loginUser.getLogin_name());
		oldGroup.setUpdateTime(new Date());
		
		Updater<SysGroup> updater = new Updater<>(oldGroup, fields+",updateBy,updateTime");
		this.update(updater);
		
		return null;
	}
	
	
	/**
	 * 删除分组
	 * @param groupids
	 * @param loginUser
	 * @param request
	 * @return
	 */
	public SysError delete(String[] groupids, LoginUser loginUser, HttpServletRequest request){
		for(String groupid : groupids){
			SysGroup group = get(groupid);
			if(group==null){
				continue;
			}
			
			if(group.getGrouptype() == 9){
				return new SysError("系统分组不能删除["+group.getGroupname()+"].");
			}
			
			Object cGroupid = getByHql("select groupid from SysGroup where pid=?", groupid);
			if(cGroupid != null){
				return new SysError("分组下存在子分组，不能删除["+group.getGroupname()+"].");
			}
			
			Object cRoleid = getByHql("select roleid from SysRole where groupid=?", groupid);
			if(cRoleid != null){
				return new SysError("分组下存在角色信息，不能删除["+group.getGroupname()+"].");
			}
			
			Object cUserid = getByHql("select userid from SysUser where groupid=?", groupid);
			if(cUserid != null){
				return new SysError("分组下存在用户信息，不能删除["+group.getGroupname()+"].");
			}
			
			this.delete(group);
		}
		return null;
	}
	
	
	
	/**
	 * 判断指定分组名是否被使用
	 * @param groupname
	 * @param groupid
	 * @param pid
	 * @return
	 */
	public boolean isNameDuplicate(String groupname, String groupid, String pid) {
		if(StringUtils.isEmpty(groupid)){
			Object id = getByHql("select groupid from SysGroup where pid=? and groupname=?", pid, groupname);
			return id!=null;
		}else {
			Object id = getByHql("select groupid from SysGroup where pid=? and groupname=? and groupid<>?", pid, groupname, groupid);
			return id!=null;
		}
	}
	
	
	/**
	 * 获取分组的全名称
	 * 
	 * @param groupid
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String[] getFullnameArray(String groupid) {
		if(groupid == null || groupid.length() % 4 != 0){
			return new String[]{};
		}
		List<String> idList = new ArrayList<String>();
		idList.add(groupid);
		while(groupid.length() > 4){
			groupid = groupid.substring(0, groupid.length()-4);
			idList.add(groupid);
		}
		
		String idset = getSqlInParam(idList);
		List<String> list = listByHql("select groupname from SysGroup where groupid in "+idset+" order by groupid asc");
		if(list==null || list.size()==0){
			return new String[]{};
		}
		String[] nameArray = new String[list.size()];
		for(int i=0, n=list.size(); i<n; i++){
			nameArray[i] = list.get(i);
		}
		return nameArray;
	}
	
	/**
	 * 获取分组的全名称
	 * @param groupid
	 * @param split
	 * @return
	 */
	public String getFullname(String groupid, String split){
		String[] nameArray = getFullnameArray(groupid);
		StringBuffer fullname = new StringBuffer();
		for(int i=0; i<nameArray.length; i++){
			if(fullname.length() > 0){
				fullname.append(split);
			}
			fullname.append(nameArray[i]);
		}
		return fullname.toString();
	}
	
	
	@SuppressWarnings("unchecked")
	public List<SysGroup> geGroupData(LoginUser loginUser){
		List<SysGroup> list = listByHql("select new com.qingxin.sys.entity.SysGroup(groupid,groupname)" +
				" from SysGroup");
		if(list == null){
			return new ArrayList<SysGroup>();
		}
		return list;
	}
	
}
